package com.dingup.provider.schedule;

import com.alibaba.fastjson.JSONObject;
import com.dingup.api.enums.ClassStatusEnum;
import com.dingup.api.model.classInfo.ClassInfo;
import com.dingup.provider.mapper.ClassInfoMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * Created by wancheng on 2018/8/31.
 */

@Component
public class ClassSchedule {

    private static Logger logger = LoggerFactory.getLogger(ClassSchedule.class);

    @Autowired
    ClassInfoMapper classInfoMapper;

    @Scheduled(cron = "0 0 0/1 * * ?")
    public void timerToNow(){
        List<ClassInfo> classInfos = classInfoMapper.getUnEndClass();
        Date currentDate = new Date();
        classInfos.stream().forEach(
            c->{
                if (currentDate.after(c.getBeginTime()) && currentDate.after(c.getEndTime())){
                    c.setStatus(ClassStatusEnum.CLASS_END);
                }else if (currentDate.after(c.getBeginTime()) && currentDate.before(c.getEndTime())){
                    c.setStatus(ClassStatusEnum.CLASS_IMPLEMENTING);
                } else if (currentDate.before(c.getBeginTime())) {
                    c.setStatus(ClassStatusEnum.CLASS_UNSTART);
                }
                ClassInfo update = new ClassInfo();
                update.setId(c.getId());
                update.setStatus(c.getStatus());
                classInfoMapper.updateByPrimaryKeySelective(update);
                logger.info("ClassSchedule 执行任务: class={} ", JSONObject.toJSONString(update));
            }
        );
    }

}
